﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.IO;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration;

namespace Oplaco.Exceptions
{
    /// <summary>
    /// Summary description for GlobalPolicyExceptionHandler.
    /// </summary>
    [ConfigurationElementType(typeof(CustomHandlerData))]
    public class ApplicationMessageExceptionHandler : IExceptionHandler
    {
        /// <summary>
        /// Construct
        /// </summary>
        /// <param name="ignore"></param>        
        public ApplicationMessageExceptionHandler(NameValueCollection ignore){}

        /// <summary>
        /// Handler method
        /// </summary>
        /// <param name="exception"></param>
        /// <param name="handlingInstanceId"></param>
        /// <returns></returns>
        public Exception HandleException(Exception exception, Guid handlingInstanceId)
        {
            return new Exception(this.ShowThreadExceptionDialog(exception), exception);
        }

        /// <summary>
        /// failsafe 
        /// </summary>
        /// <param name="ex"></param>
        /// <returns></returns>
        private String ShowThreadExceptionDialog(Exception ex) {
            
            string errorMsg = "The following exception was caught by the Quick Start Global Exception Handler:" + 
                Environment.NewLine + Environment.NewLine;

            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);

            ApplicationTextExceptionFormatter formatter = new ApplicationTextExceptionFormatter(sw, ex);
            formatter.Format();

            errorMsg += sb.ToString();
            return errorMsg;
        }
    }
}
